﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

namespace Agricultural_Sales.ASP
{
    public partial class HomeSite : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // 检查是否是从外部链接直接访问首页，如果是则清除会话以游客身份访问
                string referrer = Request.UrlReferrer?.ToString() ?? "";
                string currentUrl = Request.Url.ToString().ToLower();

                // 如果是直接访问首页或从外部链接访问，清除会话
                if (currentUrl.Contains("/home.aspx") &&
                    (string.IsNullOrEmpty(referrer) || !referrer.Contains(Request.Url.Host)))
                {
                    // 清除会话，以游客身份访问
                    Session.Clear();
                }

                LoadUserInfo();
                SetActiveNavItem();
            }
        }

        private void LoadUserInfo()
        {
            // 检查Session中是否有用户信息
            if (Session["UserId"] != null)
            {
                // 用户已登录，显示用户信息区域
                int userId = Convert.ToInt32(Session["UserId"]);
                LoadUserDetails(userId);
                ShowUserSection();
            }
            else
            {
                // 用户未登录，显示游客区域
                ShowGuestSection();
            }
        }

        private void ShowUserSection()
        {
            userInfoSection.Visible = true;
            guestSection.Visible = false;
        }

        private void ShowGuestSection()
        {
            userInfoSection.Visible = false;
            guestSection.Visible = true;
        }

        private void LoadUserDetails(int userId)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                string sql = "SELECT UserName, UserType, UserImagee FROM Users WHERE UserId = @UserId";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddWithValue("@UserId", userId);

                    try
                    {
                        conn.Open();
                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                lblUserName.Text = reader["UserName"].ToString();
                                lblUserType.Text = reader["UserType"].ToString();

                                string imagePath = reader["UserImagee"].ToString();
                                if (!string.IsNullOrEmpty(imagePath))
                                {
                                    imgUserAvatar.ImageUrl = imagePath;
                                }
                                else
                                {
                                    imgUserAvatar.ImageUrl = "~/Image/user1.jpg";
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // 错误处理，显示游客状态
                        ShowGuestSection();
                    }
                }
            }
        }

        private void SetActiveNavItem()
        {
            string currentPage = Request.Url.AbsolutePath.ToLower();

            // 移除所有导航项的active类
            lnkHome.CssClass = "nav-item";
            lnkProfile.CssClass = "nav-item";
            lnkOrders.CssClass = "nav-item";
            lnkAbout.CssClass = "nav-item";

            // 根据当前页面设置active类
            if (currentPage.Contains("/home.aspx"))
            {
                lnkHome.CssClass = "nav-item active";
            }
            else if (currentPage.Contains("/myuserinfo.aspx"))
            {
                lnkProfile.CssClass = "nav-item active";
            }
            else if (currentPage.Contains("/myorder.aspx"))
            {
                lnkOrders.CssClass = "nav-item active";
            }
            else if (currentPage.Contains("/about.aspx"))
            {
                lnkAbout.CssClass = "nav-item active";
            }
        }

        protected void lnkLogout_Click(object sender, EventArgs e)
        {
            // 清除Session
            Session.Clear();
            Session.Abandon();

            // 重定向到登录页面
            Response.Redirect("~/ASP/Login.aspx");
        }

        protected void lnkGuestAvatar_Click(object sender, EventArgs e)
        {
            // 游客头像点击事件，跳转到登录页面
            Response.Redirect("~/ASP/Login.aspx");
        }

        // 添加新方法：强制以游客身份访问
        protected void ForceGuestMode()
        {
            Session.Clear();
            Session.Abandon();
            ShowGuestSection();
        }
    }
}